var event = require('../../core/event');
var util = require('../../util/index');
var Log = require('../../util/logger');
var ui = require('./ui');
var note = require('../note/manager');
var fs = require('fs');


var fileHistory = [];
var changed = false;
var _init = false;

var ret = {
	init: function(){
		if(_init){
			return;
		}
		var self = this;
		//加载最近打开的file
		var path = util.getWorkingPath('./cache/history.json');
		util.loadJson(path).then(function(data){
			var len = data.length;
			while(len > 5){
				data.pop();
				len--;
			}
			//可能有些文件不存在了, 移除
			for(var i=len-1;i>=0;i--){
				var path = data[i].path;
				if(!fs.existsSync(path)){
					data.splice(i, 1);
				}
			}
			fileHistory = data;
		}).catch(function(e){
			Log.log("load history failed", 1);
		}).finally(function(){
			self.openDialog();
		});
		event.bind(event.events.note.load, "welcome", this);
		event.bind(event.events.dialog.welcome, "welcome", this);
		Log.log('welcome init');
		_init = true;
	},

	release: function(){
		if(!changed){
			return;
		}
		var path = util.getWorkingPath('./cache/history.json');
		util.saveJsonSync(path, fileHistory);
	},

	_getHistory: function(){
		return fileHistory;
	},

	_pickAt: function(idx){
		var record = fileHistory[idx];
		if(!record){
			return;
		}
		note.load(record.path);
	},

	onEvent: function (e, param) {
		if(e == event.events.note.load) {
			var file = param.path;
			if(!file) {
				return;
			}
			var idx = file.lastIndexOf('/');
			var name = file;
			if(idx > 0) {
				name = file.substring(idx + 1);
			}
			//删掉相同file
			for(var i = 0; i < fileHistory.length; i++) {
				if(fileHistory[i].path == file) {
					fileHistory.splice(i, 1);
					break;
				}
			}
			fileHistory.unshift({
				name: name,
				path: file
			});
			if(fileHistory.length > 5) {
				fileHistory.pop();
			}
			changed = true;
		}else if(e == event.events.dialog.welcome){
			this.openDialog();
		}
	},

	openDialog: function () {
		ui.init();
		ui.setManager(this);
		ui.show();
	}

};

module.exports = ret;
